import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

/**
 * 路由状态管理 Store
 * 集成观察者模式，管理全局路由状态
 */
export const useRouteStore = defineStore('route', () => {
  // 状态
  const currentRoute = ref(null)
  const routeHistory = ref([])
  const breadcrumbs = ref([])
  const isLoading = ref(false)
  const redirectPath = ref(null)

  // 用户相关状态
  const isAuthenticated = ref(false)
  const userInfo = ref({
    username: '',
    avatar: '',
    token: ''
  })

  // 缓存状态
  const cachedData = ref({
    knowledge: null,
    departments: null,
    userAppointments: null
  })

  // 计算属性
  const currentPageName = computed(() => {
    return currentRoute.value?.name || '未知页面'
  })

  const canGoBack = computed(() => {
    return routeHistory.value.length > 1
  })

  const previousRoute = computed(() => {
    const history = routeHistory.value
    return history.length > 1 ? history[history.length - 2] : null
  })

  // 页面标题映射
  const pageTitles = computed(() => ({
    '/': '用户登录',
    '/home': '首页',
    '/knowledge': '知识库',
    '/appointment': '预约挂号',
    '/about': '关于我们',
    '/my-appointments': '我的预约'
  }))

  // Actions
  const updateCurrentRoute = (routeInfo) => {
    currentRoute.value = routeInfo
    
    // 更新历史记录
    if (!routeHistory.value.some(r => r.fullPath === routeInfo.fullPath)) {
      routeHistory.value.push(routeInfo)
      
      // 限制历史记录长度
      if (routeHistory.value.length > 20) {
        routeHistory.value = routeHistory.value.slice(-15)
      }
    }
  }

  const updateBreadcrumbs = (breadcrumbList) => {
    breadcrumbs.value = breadcrumbList
  }

  const setLoading = (loading) => {
    isLoading.value = loading
  }

  const setRedirectPath = (path) => {
    redirectPath.value = path
  }

  const clearRedirectPath = () => {
    redirectPath.value = null
  }

  // 用户认证相关
  const setAuthenticated = (status) => {
    isAuthenticated.value = status
  }

  const setUserInfo = (info) => {
    userInfo.value = { ...userInfo.value, ...info }
  }

  const logout = () => {
    isAuthenticated.value = false
    userInfo.value = {
      username: '',
      avatar: '',
      token: ''
    }
    localStorage.removeItem('token')
    sessionStorage.removeItem('token')
  }

  // 缓存管理
  const setCachedData = (key, data) => {
    cachedData.value[key] = data
  }

  const getCachedData = (key) => {
    return cachedData.value[key]
  }

  const clearCache = (key = null) => {
    if (key) {
      cachedData.value[key] = null
    } else {
      cachedData.value = {
        knowledge: null,
        departments: null,
        userAppointments: null
      }
    }
  }

  // 路由历史导航
  const goBack = () => {
    if (canGoBack.value) {
      const prevRoute = previousRoute.value
      return prevRoute
    }
    return null
  }

  const getRouteTitle = (path) => {
    return pageTitles.value[path] || '页面'
  }

  // 调试方法
  const getDebugInfo = () => {
    return {
      currentRoute: currentRoute.value,
      routeHistory: routeHistory.value,
      breadcrumbs: breadcrumbs.value,
      isAuthenticated: isAuthenticated.value,
      cachedDataKeys: Object.keys(cachedData.value).filter(key => cachedData.value[key] !== null)
    }
  }

  return {
    // 状态
    currentRoute,
    routeHistory,
    breadcrumbs,
    isLoading,
    redirectPath,
    isAuthenticated,
    userInfo,
    cachedData,

    // 计算属性
    currentPageName,
    canGoBack,
    previousRoute,
    pageTitles,

    // Actions
    updateCurrentRoute,
    updateBreadcrumbs,
    setLoading,
    setRedirectPath,
    clearRedirectPath,
    setAuthenticated,
    setUserInfo,
    logout,
    setCachedData,
    getCachedData,
    clearCache,
    goBack,
    getRouteTitle,
    getDebugInfo
  }
})